package com.ada.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

public class MyInterceptor implements HandlerInterceptor {
    //记录一下登陆
    public HashMap<String,String> hashMap=new HashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        response.setHeader("Access-Control-Allow-Origin", "http://localhost"); // 允许跨域请求
//        response.setHeader("Access-Control-Allow-Credentials", "true");

        if(request.getRequestURI().equals("/resume/logout")){
            hashMap.remove("admin");
            reDirect(request,response,"/login.jsp");
            return false;
        }
        if(request.getRequestURI().equals("/resume/login")){
            String name=((String[])request.getParameterMap().get("name"))[0];
            String password=((String[])request.getParameterMap().get("password"))[0];
            if("admin".equals(name)&&"admin".equals(password)){
                hashMap.put("admin","admin");
                reDirect(request,response,"/index.jsp");
            }else {
                reDirect(request,response,"/login.jsp");
            }
            return false;
        }
        if(!hashMap.containsKey("admin")){
            reDirect(request,response,"/login.jsp");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    // 对于请求是ajax请求重定向问题的处理方法
    public void reDirect(HttpServletRequest request, HttpServletResponse response,String url) throws IOException {
        // 获取当前请求的路径
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        // 如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            // 告诉ajax我是重定向
            response.setHeader("REDIRECT", "REDIRECT");
            // 告诉ajax我重定向的路径
            response.setHeader("CONTENTPATH", basePath + url);
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
        } else {
            response.sendRedirect(basePath + url);
        }
    }

}
